package com.otojob.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.otojob.constant.WeChatConstant;
import com.otojob.dto.WxLoginDTO;
import com.otojob.entity.User;
import com.otojob.mapper.UserMapper;
import com.otojob.service.WechatAuthService;
import com.otojob.utils.HttpClientUtils;
import com.otojob.utils.JwtUtils;
import com.otojob.utils.Results;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Author: TingFeng
 * @CreateTime: 2022/3/25  18:47
 */
@Slf4j
@Service
public class WechatAuthServiceImpl implements WechatAuthService {
    @Resource
    private HttpServletRequest request;


    @Resource
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;



    /**
     * 微信登录认证
     * @param wxLoginDTO 微信登录参数
     * @return 是否成功
     */
//    @Cacheable(value = "wx",key = "'token'")
    @Override
    public Results wechatLogin(WxLoginDTO wxLoginDTO) {
        String openId = getOpenId(wxLoginDTO.getCode());
        if (openId==null){
            return Results.error().message("用户不存在");
        }
        //判断用户是否存在
        int i = userMapper.findUserByOpenId(openId);
        //不存在就创建一个新用户
        if(i==0){
            User user = new User();
            user.setOpenId(openId);
            user.setNickname(wxLoginDTO.getNickName());
            user.setDeclaration("介绍一下你自己");
            user.setSex("男");
            user.setPhoto(wxLoginDTO.getAvatarUrl());
            //添加用户
            userMapper.addUser(user);
            log.info("创建用户成功");

        }
        //通过openid得到用户id
        int id = userMapper.findIdByOpenId(openId);
        String jwtToken = JwtUtils.getJwtToken(id, wxLoginDTO.getNickName());
        log.info("登入成功"+jwtToken);

        return Results.ok().data("token",jwtToken);

    }

    /**
     * 校验Token的合法性
     * @return
     */
    @Override
    public Results checkToken() {
        boolean b = JwtUtils.checkToken(request);

        if (b){
            String token = request.getHeader("token");
            //重新设置缓存时间
            redisTemplate.opsForValue().set("wx::token",token,30L,TimeUnit.DAYS);
            return Results.ok();
        }
        return Results.error().message("用户未登入");

    }

    /**
     * 调用微信接口获取openid 进行登录凭证校验
     *
     * @param code
     * @return
     */
    public String getOpenId(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
                "appid=" + WeChatConstant.APP_ID+ "&secret="
                + WeChatConstant.SECRET + "&js_code=" + code + "&grant_type=authorization_code";

        try {

            //请求这个拼接好的地址，得到返回两个值 accsess_token 和 openid
            //使用httpclient发送请求，得到返回结果
            String accessTokenInfo = HttpClientUtils.get(url);
            System.out.println(accessTokenInfo);
            //从accessTokenInfo字符串获取 openid
            //把accessTokenInfo字符串转换map集合，根据map里面key获取对应值
            //使用json转换工具 Gson
            Gson gson = new Gson();
            HashMap mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
            //微信唯一ID值
            String openid = (String)mapAccessToken.get("openid");
            if(openid==null||openid.length()==0){
                throw new RuntimeException("登入凭证错误");
            }
            return openid;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
